package com.jtech.together.view.activity;

import android.Manifest;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.autonavi.amap.mapcore.Inner_3dMap_location;
import com.jtech.together.R;
import com.jtech.together.mvp.contract.LocationContract;
import com.jtech.together.mvp.presenter.LocationPresenter;
import com.jtech.together.view.activity.base.BaseActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.umeng.analytics.MobclickAgent;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 位置选择
 * Created by wuxubaiyang on 2017/5/11.
 */
public class LocationActivity extends BaseActivity implements LocationContract.View, View.OnClickListener {
    public static final String KEY_LOCATION = "keyLocation";
    public static final String KEY_LOCATION_TITLE = "keyLocationTitle";
    public static final String KEY_LOCATION_DESCRIBE = "keyLocationDescribe";
    public static final String KEY_LOCATION_ADDRESS = "keyLocationAddress";

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.mapview_location)
    MapView mapView;
    @Bind(R.id.fab_location)
    FloatingActionButton fabDone;

    private LocationContract.Presenter presenter;
    private AMap aMap;

    @Override
    protected void initVariables(Bundle bundle) {
        //绑定P类
        presenter = new LocationPresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_location);
        //onCreate
        mapView.onCreate(savedInstanceState);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置后退按钮
        toolbar.setNavigationOnClickListener(this);
        //初始化地图控制器对象
        aMap = mapView.getMap();
    }

    @Override
    protected void loadData() {
        //设置目标位置
        double[] location = presenter.getLocation();
        if (null != location) {
            setTarget(new LatLng(location[0], location[1]));
        } else {
            setMyLocation();
        }
    }

    /**
     * 设置我的位置
     */
    private void setMyLocation() {
        Dexter.withActivity(getActivity())
                .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        MyLocationStyle myLocationStyle = new MyLocationStyle();
                        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
                        aMap.setMyLocationStyle(myLocationStyle);
                        aMap.getUiSettings().setMyLocationButtonEnabled(true);
                        aMap.setMyLocationEnabled(true);
                        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
                            @Override
                            public void onMyLocationChange(Location location) {
                                //获取到位置并且没有目标作为参数传进来则显示fab
                                if (null != location) {
                                    fabDone.show();
                                    scrollToCenter(new LatLng(location.getLatitude(), location.getLongitude()));
                                }
                            }
                        });
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        onBackPressed();
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();
    }

    /**
     * 设置目标点标记
     *
     * @param targetLatLng
     */
    private void setTarget(LatLng targetLatLng) {
        toolbar.setTitle(presenter.getLocationTitle());
        MarkerOptions markerOptions = new MarkerOptions()
                .position(targetLatLng)
                .title(presenter.getLocationTitle())
                .snippet(presenter.getLocationDescribe());
        aMap.addMarker(markerOptions);
        //地图操作
        scrollToCenter(targetLatLng);
    }

    /**
     * 完成按钮点击事件
     */
    @OnClick(R.id.fab_location)
    public void onDoneClick() {
        Intent data = new Intent();
        //获取坐标
        Inner_3dMap_location location = (Inner_3dMap_location) aMap.getMyLocation();
        data.putExtra(KEY_LOCATION, new double[]{location.getLongitude(), location.getLatitude()});
        data.putExtra(KEY_LOCATION_ADDRESS, location.getAddress());
        setResult(RESULT_OK, data);
        onBackPressed();
    }

    /**
     * 滚动到中心点
     *
     * @param targetLatLng
     */
    private void scrollToCenter(LatLng targetLatLng) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(targetLatLng, 15f);
        aMap.animateCamera(cameraUpdate);
    }

    @Override
    public void onClick(View v) {
        //后退
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
}